package com.aikg.kgrag_java.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

/**
 * @ClassName: JsonUtils
 * @Description: Json工具类
 * @Author: 李宗雨
 * @Date: 2024/12/26 18:25
 * @Version: 1.0
 **/
public class JsonUtils {
    private static final ObjectMapper jsonMapper = new ObjectMapper();

    public static <T> T toObj(String str, Class<T> clz) {
        try {
            return jsonMapper.readValue(str, clz);
        } catch (JsonProcessingException e) {
            throw new UnsupportedOperationException(e);
        }
    }

    public static <T> T toObj(String str, TypeReference<T> clz) {
        try {
            return jsonMapper.readValue(str, clz);
        } catch (JsonProcessingException e) {
            throw new UnsupportedOperationException(e);
        }
    }

    public static <T> List<T> toList(String str, Class<T> clz) {
        try {
            return jsonMapper.readValue(str, new TypeReference<List<T>>() {
            });
        } catch (JsonProcessingException e) {
            throw new UnsupportedOperationException(e);
        }
    }

    public static JsonNode toJsonNode(String str) {
        try {
            return jsonMapper.readTree(str);
        } catch (JsonProcessingException e) {
            throw new UnsupportedOperationException(e);
        }
    }

    public static <T> T nodeToValue(JsonNode node, Class<T> clz) {
        try {
            return jsonMapper.treeToValue(node, clz);
        } catch (JsonProcessingException e) {
            throw new UnsupportedOperationException(e);
        }
    }

    public static String toStr(Object t) {
        try {
            return jsonMapper.writeValueAsString(t);
        } catch (Exception e) {
            throw new UnsupportedOperationException(e);
        }
    }

//    public static void main(String[] args) {
////        System.out.println(JsonUtils.toJsonNode("{ \"name\" : \"汉字\", \"age\" : 28, \"height\": 1.75, \"ok\": true}"));
//        String a = "{\"code\": 200, \"message\": \"Success\", \"data\": \"SSE 是一种 HTML5 Web API，允许网页从服务器接收实时更新。与传统的请求 - 响应模式不同，SSE 提供了单向的、服务器到客户端的实时消息推送机制。在 FastAPI 中实现 SSE 可以用于实时数据更新场景，如实时日志显示、实时监控数据推送等。\" }";
//
//        Response re = JsonUtils.toObj(a, Response.class);
//        System.out.println(re.getData());
//    }
}

